import router from './index'
import { Route } from 'uni-simple-router'
import Vue from 'vue'
import { fullPageCatch } from '@/common/config'
const that_ = Vue.prototype;

// #ifdef H5
// import wechatShare from '@/mixins/share'
// #endif

//全局路由前置守卫
router.beforeEach((to, from, next) => {
    //之后可能加其他的，可以用来做登录返回上一页
    if(to.query.action === "referrer"){
        delete to.query.action;
        next({
            NAVTYPE: 'push',
            name: to.name,
            query: {
                lastName: from.name,
                lastQuery: JSON.stringify({...from.query}),
                prevPath: from.path,
                ...to.query
            }
        })
        return ;
    }
    next()
})

// 全局路由后置守卫
router.afterEach(async (to, from) => {
    /**
	 * 调用埋点
	*/
	let userInfo = await that_.$http('userInfo', {}, {
		source: 'catch'
	});
	userInfo.uid && guestRecord(to, from);

	/**
	 * 打烊之后页面不显示，就要请求店铺基本信息
	*/
	let { meta = {} } = to;
	if(meta.storeClose !== 'show'){
		let { data } = await that_.$http('shopInfo');
		if(data.status === 0 && to.name !== 'storeClose'){
			return router.push({
				name: 'storeClose',
				params: {
					lastName: from.name,
					lastQuery: JSON.stringify({...from.query}),
					prevPath: from.path,
					...to.query
				}
			})
		}
	}
	// 进入页面之前注销掉所有的广播监听,不然会产生一些不可预料是事情
	uni.$off('pageReachBottom');
	uni.$off('pagePullDownRefresh');
	uni.$off('pageShow');
	uni.$off('pageHide');
	// storeClose
	
	// 设置页面路径
	// that_.$store.dispatch('config/setPagePath', {
	// 	to: to,
	// 	from: from
	// })
	
	uni.setStorageSync(fullPageCatch, `${to.path}${parse(to.query)}`)

	// #ifdef H5
	if(that_.$isWechatBrowser){
		//微信浏览器隐藏头部
		// let uniPageHead = (document as any).querySelector('[uni-page-head-type="default"]');
		// uniPageHead && uniPageHead.remove();
		// (document as any).querySelector('body').classList.add('wx-browser');
		if(!to.query.detailId || !(to.meta && to.meta.special)){//不是文章类分享内容都是一致的
			let authUrl = router.$route.history.current.fullPath;
			if (uni.getSystemInfoSync().platform === 'ios') {// IOS
				wechatShare.call(that_, { authUrl });
			} else {
				// 安卓
				setTimeout(() => {
					wechatShare.call(that_, { authUrl });
				}, 100);
			}
		}
	}
	// #endif

})

/** *
 * 埋点
 */
async function guestRecord(to, from) {
	let { data: { token } } = await Vue.prototype.$http('wxuserinfo', null, {
		source: 'catch'
	});
	if (!token) return false
	that_.$http('setGuestRecord', {
		relate_id: to.query.detailId || to.query.id || '',
		relate_type: to.meta ? to.meta.type_id : '',
		share_user_id: to.query.share_user_id,
		platform_type: platformType
	})
}


export const parse = (query = {}) => {
    return Object.keys(query)
        .filter(key => !isEmpty(query[key]))
        .reduce((result, key) => {
            const value = query[key]
            // in查询特殊处理
            if (Array.isArray(value) && !isEmpty(value)) {
                return `${result}&${value.reduce((val, cVal) => `${val ? `${val}&` : val}${key}=${cVal}`, '')}`
            }

            // between查询做特殊处理
            if (typeof value === 'object' && !isEmpty(value)) {
                const [start, end] = value
                return `${result}&${key}[]=${start}&${key}[]=${end}`
            }

            return `${result}&${key}=${value}`
        }, '')
        .replace(/^&/, '?')
}
